<script setup>
import { User , Lock , Key ,Cellphone} from '@element-plus/icons-vue'
import {inject, ref} from 'vue'
import {useRouter} from "vue-router";
import { ElMessage } from 'element-plus'
const router = useRouter();

const activeName = ref('first')
const handleClick = (tab, event) => {
  console.log(tab, event)
}
//控制注册界面的显示，重置密码界面的显示
let isRegister = ref(false)
let isReset = ref(false)
//登录信息
const LoginByNameData = ref({
  username:'',
  password:'',
  code:''
})
const LoginByPhoneData = ref({
  phoneNumber:'',
  phoneCode:''
})
const RegisterData = ref({
  username:'',
  password:'',
  rePassword:'',
  phoneNumber:'',
  phoneCode:''
})
const ResetPasswordData = ref({
  phoneNumber:'',
  password:'',
  rePassword:'',
  phoneCode:''
})
//用户名登录接口调用
import {
  // userLoginByGitee,
  userLoginByNameService,
  userLoginByPhoneService,
  userRegisterByPhoneService,
  // userRegisterByGitee,
  resetPasswordService, sendPhoneCodeLoginService, sendPhoneCodeRegisterService, sendPhoneCodeResetService
} from '@/api/user.js'
import {getLoginForm, getRegisterForm} from "@/api/gitee";
//用户名登录
const loginByName = async ()=>{
  let result = await userLoginByNameService(LoginByNameData.value);
  if(result.status === 1){
    //存token到本地
    localStorage.setItem("token", result.data.token);
    localStorage.setItem("username", result.data.username);
    isSignIn.value='true';
    router.push('/main');



  }else{
    ElMessage.error(result.message);
    router.push('/login')
  }
}
//手机号登录
const loginByPhone = async ()=>{
  let result = await userLoginByPhoneService(LoginByPhoneData.value);
  if(result.status === 1){
    localStorage.setItem("token", result.data.token);
    localStorage.setItem("username", result.data.username);
    isSignIn.value='true';
    router.push('/main');

  }else{
    ElMessage.error(result.message);
    router.push('/login')
  }
}
//发送登录验证码
const sendPhoneCodeLogin = async (phoneNumber)=>{
  let result = await sendPhoneCodeLoginService(phoneNumber);
  if(result.status === 1){
    ElMessage.success(result.message);
  }else{
    ElMessage.error(result.message);
  }
}
//gitee登录
//?
const loginByGitee = async ()=>{
  let res = await getLoginForm();
  if(res.status === 1){
    window.location.href= res.data;
  }
  // window.location.href= url;
}
//gitee注册
//?
const registerByGitee = async ()=>{
  let res = await getRegisterForm();
  if(res.status === 1){
    window.location.href= res.data;
  }
}
//普通注册
//校验两次密码是否相同
const checkRePassword = (rule,value,callback)=>{
  if(value===''){
    callback(new Error('请再次确认密码'))
  }else if(value !== RegisterData.value.password){
    callback(new Error('密码不一致'))
  }else {
    callback()
  }
}
//判断手机号是否已被使用
const checkPhoneNumberExists = (rule, value, callback) => {
  return new Promise((resolve) => {
    fetch(`http://localhost:8080/users/phone/${value}`)
        .then(response => {
          if (!response.ok) {
            callback(new Error('网络响应失败'));
          }
          return response.json();
        })
        .then(data => {
          if (data.status === 1) {
            callback(new Error('手机号已存在，请更换手机号！'));
            resolve(false);
          } else {
            // callback();
            resolve(true);
          }
        })
        .catch(error => {
          console.log(error)
          // callback(error);
          // reject(error);
        });
  });
};
//判断用户名是否已存在
const checkUsernameExists = (rule, value, callback) => {
  return new Promise((resolve) => {
    fetch(`http://localhost:8080/users/username/${value}`)
        .then(response => {
          if (!response.ok) {
            callback(new Error('网络响应失败'));
          }
          return response.json();
        })
        .then(data => {
          if (data.status === 1) {
            callback(new Error('用户名已存在，请更换用户名！'));
            resolve(false);
          } else {
            // callback();
            resolve(true);
          }
        })
        .catch(error => {
          console.log(error)
          // callback(error);
          // reject(error);
        });
  });
};
//发送注册验证码
const sendPhoneCodeRegister = async (phoneNumber)=>{
  let result = await sendPhoneCodeRegisterService(phoneNumber);
  if(result.status === 1){
    ElMessage.success(result.message);
  }else{
    ElMessage.error(result.message);
  }
}
const register = async () =>
{
  try {
    let phoneNumberExists = await checkPhoneNumberExists(RegisterRules,null, RegisterData.value.phoneNumber);
    let usernameExists = await checkUsernameExists(RegisterRules,null, RegisterData.value.username);
    if (usernameExists && phoneNumberExists) {
      let result = await userRegisterByPhoneService(RegisterData.value);
      console.log('status='+result.status)
      if (result.status=== 1) {
        // localStorage.setItem("token", result.data.token);
        // localStorage.setItem("username", result.data.username);
        ElMessage.success(result.message);
        isRegister.value = false;

        await router.push('/login');
      } else {
        ElMessage.error(result.message);
      }
    }else{
      Element.error("请检查用户名或手机号是否已被占用")
    }
  } catch (error) {
    console.error('error:', error);
  }
}
//重置密码
const resetPassword = async ()=>{
  let result = await resetPasswordService(ResetPasswordData.value);
  console.log(result);
  if(result.status === 1){
    ElMessage.success(result.message);
    isReset = false;
    router.go(0);
  }else{
    ElMessage.error(result.message);
  }
}
const sendPhoneCodeReset = async (phoneNumber)=>{
  let result = await sendPhoneCodeResetService(phoneNumber);
  console.log(result)
  if(result.status === 1){
    ElMessage.success(result.message);
  }else{
    ElMessage.error(result.message);
  }
}
const isSignIn = inject('isSignIn')
const isSearch = inject('isSearch')
// const webSocket=inject('')
isSearch.value=false;
//定义表单校验规则
const LoginRules = {
  username:[
    {required: true, message:'请输入用户名',trigger:'blur'},
    {min:1,max:20,message: '请输入长度为1-20位非空字符',trigger: 'blur'},
  ],
  password:[
    {required: true, message:'请输入密码',trigger:'blur'},
    {min:1,max:20,message: '请输入长度为1-20位非空字符',trigger: 'blur'}
  ],
  code:[
    {required: true, message:'请输入验证码',trigger:'blur'}
  ],
  phoneNumber:[
    {required: true, message:'请输入手机号',trigger:'blur'},
    {required: true, max:11,pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确',trigger: 'blur'},
  ],
  phoneCode:[
    {required: true, message:'请输入验证码',trigger:'blur'}
  ],
}
const RegisterRules = {
  username:[
    {required: true, message:'请输入用户名',trigger:'blur'},
    {min:1,max:20,message: '请输入长度为1-20位非空字符',trigger: 'blur'},
    { validator: checkUsernameExists, trigger: 'blur'}
  ],
  password:[
    {required: true, message:'请输入密码',trigger:'blur'},
    {min:1,max:20,message: '请输入长度为1-20位非空字符',trigger: 'blur'}
  ],
  code:[
    {required: true, message:'请输入验证码',trigger:'blur'}
  ],
  phoneNumber:[
    {required: true, message:'请输入手机号',trigger:'blur'},
    {required: true, max:11,pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确',trigger: 'blur'},
    {validator: checkPhoneNumberExists, trigger: 'blur'}
  ],
  phoneCode:[
    {required: true, message:'请输入验证码',trigger:'blur'}
  ],
  rePassword:[
    {validator:checkRePassword,trigger:'blur'}
  ]
}
//用户名登录接口调用
// import {userLoginByNameSevice} from '@/api/user.js'
// import router from "@/router";
// const loginByName = async ()=>{
//   // console.log(LoginData.value);
//   let result = await userLoginByNameSevice(LoginData.value);
//   if(result.status === 1){
//     // console.log(result);
//     // console.log(result.data);
//      console.log(result.data.username);
//     alert("登录成功！");
//     isSignIn.value='true';
//     localStorage.setItem("token", result.data.token);
//     localStorage.setItem("username",result.data.username);
//     await router.push('/');
//   }else{
//     alert("登录失败")
//   }
// }

</script>

<template>
  <el-main>
  <div class="center-wrapper">
    <!-- 登录卡片界面-->
  <el-card style="max-width: 480px" v-if="!isReset && !isRegister">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" stretch="true">
      <el-tab-pane label="账号密码登录" name="first">
        <!--账号密码登录表单-->
        <el-form ref="form" label-width="auto" style="max-width: 600px" :model="LoginByNameData" :rules="LoginRules">
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" size="large" style="width: 350px" v-model="LoginByNameData.username"/>
          </el-form-item>
          <el-form-item prop="password">
            <el-input :prefix-icon="Lock" show-password type="password" size="large"
                  placeholder="请输入密码" v-model="LoginByNameData.password"/>
          </el-form-item>
          <el-form-item prop="code">
            <el-input :prefix-icon="Key" placeholder="请输入验证码" size="large" v-model="LoginByNameData.code">
              <template #suffix>
                  <img alt="单击图片刷新！" class="pointer" src="http://localhost:8080/common/kaptcha" style="position: absolute;right: 0; "
                       onclick="this.src='http://localhost:8080/common/kaptcha?d='+new Date()*1">
              </template>
            </el-input>
          </el-form-item>
          <div class="divLink" style="text-align: right">
            <el-link type="info" style="margin: 0 3px; font-size: 16px" @click="isReset = true;isRegister = false">忘记密码</el-link>
          </div>
          <el-form-item>
            <el-button class="button" type="primary" style="width: 100%;font-size: 18px" @click="loginByName" size="large">登 录</el-button>
          </el-form-item>
          <div class="divLink">
            <el-link type="info" style="margin: 0 3px; float: left;font-size: 16px" @click="loginByGitee">第三方登录</el-link>
            <el-link type="info" style="margin: 0 3px; float: right;font-size: 16px" @click="isRegister = true;isReset = false">没有账号？去注册</el-link>
          </div>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="手机号登录" name="second">
        <!--手机号登录表单-->
        <el-form ref="form" label-width="auto" style="max-width: 600px" :model="LoginByPhoneData" :rules="LoginRules">
          <el-form-item prop="phoneNumber">
            <el-input :prefix-icon="Cellphone" placeholder="请输入手机号" style="width: 350px" size="large" v-model="LoginByPhoneData.phoneNumber"/>
          </el-form-item>
          <el-form-item prop="phoneCode">
            <el-input :prefix-icon="Key" placeholder="请输入验证码" size="large" v-model="LoginByPhoneData.phoneCode">
              <template #append>
                <el-button @click="sendPhoneCodeLogin(LoginByPhoneData.phoneNumber)" style="max-width: 100px;">获取验证码</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="button" type="primary" style="width: 100%;font-size: 20px" size="large" @click="loginByPhone">登 录</el-button>
          </el-form-item>
          <div class="divLink">
            <el-link type="info" style="margin: 0 3px; float: left; font-size: 15px" @click="loginByGitee">第三方登录</el-link>
            <el-link type="info" style="margin: 0 3px; float: right; font-size: 15px" @click="isRegister = true">没有账号？去注册</el-link>
          </div>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-card>
    <!-- 注册卡片界面-->
    <el-card style="max-width: 480px" autocomplete="off" v-if="isRegister">
          <!--注册表单-->
          <el-form ref="form" label-width="auto" style="max-width: 600px" :model="RegisterData" :rules="RegisterRules">
            <el-form-item style="text-align: center;">
              <h3 style="text-align: center; margin: auto; font-size: 25px">注  册</h3>
            </el-form-item>
            <el-form-item prop="username" style="margin: 20px 40px">
              <el-input :prefix-icon="User" placeholder="请输入用户名" size="large" style="width: 350px;" v-model="RegisterData.username"/>
            </el-form-item>
            <el-form-item prop="password" style="margin: 20px 40px">
              <el-input show-password type="password" placeholder="请输入密码" size="large"
                        :prefix-icon="Lock"  v-model="RegisterData.password"/>
            </el-form-item>
            <el-form-item prop="rePassword" style="margin: 20px 40px">
              <el-input show-password type="password" placeholder="请再次输入密码" size="large"
                        :prefix-icon="Lock" v-model="RegisterData.rePassword"/>
            </el-form-item>
            <el-form-item prop="phoneNumber" style="margin: 20px 40px">
              <el-input :prefix-icon="Cellphone" placeholder="请输入手机号" size="large" v-model="RegisterData.phoneNumber"/>
            </el-form-item>
            <el-form-item prop="phoneCode" style="margin: 20px 40px">
              <el-input :prefix-icon="Key" placeholder="请输入验证码" size="large" v-model="RegisterData.phoneCode">
                <template #append>
                  <el-button @click="sendPhoneCodeRegister(RegisterData.phoneNumber)" style="max-width: 100px;font-size: 15px">获取验证码</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button class="button" type="primary" size="large" style="width: 80%;font-size: 20px;margin: 0 auto;" @click="register()">注 册</el-button>
            </el-form-item>
            <div class="divLink" style="margin: 5px 40px 15px 40px">
              <el-link type="info" style="margin: 0 3px 15px 0; float: left; font-size: 15px" @click="registerByGitee">第三方注册</el-link>
              <el-link type="info" style="margin: 0 3px 15px 0; float: right; font-size: 15px" @click="isRegister = false">返回登录</el-link>
            </div>
          </el-form>
    </el-card>
    <!-- 重置密码界面-->
    <el-card style="max-width: 480px" autocomplete="off" v-if="isReset" >
      <!--重置密码表单-->
      <el-form ref="form" label-width="auto" style="max-width: 600px" :model="ResetPasswordData" :rules="LoginRules">
        <el-form-item style="text-align: center;">
          <h3 style="text-align: center; margin: 0 auto; font-size: 23px">重 置 密 码</h3>
        </el-form-item>
        <el-form-item prop="phoneNumber" style="margin: 20px 40px">
          <el-input :prefix-icon="Cellphone" placeholder="请输入手机号" size="large" v-model="ResetPasswordData.phoneNumber"/>
        </el-form-item>
        <el-form-item prop="password" style="margin: 20px 40px">
          <el-input show-password type="password" placeholder="请输入新密码" size="large"
                    :prefix-icon="Lock" v-model="ResetPasswordData.password"/>
        </el-form-item>
        <el-form-item prop="rePassword" style="margin: 20px 40px">
          <el-input show-password type="password" placeholder="请再次输入密码" size="large"
                    :prefix-icon="Lock"  v-model="ResetPasswordData.rePassword"/>
        </el-form-item>
        <el-form-item prop="phoneCode" style="margin: 20px 40px">
          <el-input :prefix-icon="Key" placeholder="请输入验证码" size="large" v-model="ResetPasswordData.phoneCode">
            <template #append>
              <el-button @click="sendPhoneCodeReset(ResetPasswordData.phoneNumber)" style="max-width: 100px;font-size: 15px">获取验证码</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" size="large" style="width: 80%;font-size: 20px;margin: 0 auto;" @click="resetPassword">重 置</el-button>
        </el-form-item>
        <div class="divLink" style="margin: 5px 40px 15px 40px">
          <el-link type="info" style="margin: 0 3px 15px 0; float: left;"  @click="isReset = false">返回登录</el-link>
          <el-link type="info" style="margin: 0 3px 15px 0; float: right;" @click="isRegister = true;isReset = false">没有账号？去注册</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
  </el-main>

</template>


<style>

/*//element*/
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
  text-align: center;
}
.center-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-link {
  margin-right: 8px;
}
.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}
</style>